<template>
  <div class="show-info">
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="旧密码" prop="pass">
        <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="checkPass">
        <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass1">
        <el-input type="password" v-model="ruleForm.checkPass1" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleForm)">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { changePassword } from '@/api/auth/index.js'
export default {
  mounted() {

  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass1');
        }
        callback();
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.checkPass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }
    return {
      ruleForm: {
        pass: '',
        checkPass: '',
        checkPass1: '',
      },
      rules: {
        pass: [
          { required: true, message: '请输入原始密码', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        checkPass: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass1: [
          { required: true, message: '两次输入密码不一致', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    submitForm(ruleForm) {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) { return }
        changePassword(ruleForm).then(r => {
          if (r.code == 200) {
            this.$message.success(r.msg);
            this.$router.push("/Login");
            return;
          }
          this.$message.error(r.msg);
        });
      })
    },
    resetForm(ruleForm) {
      this.$refs.ruleForm.resetFields();
    }
  }
}
</script>

<style scoped>
.show-info {
  margin-left: 35%;
  margin-top: 100px;
  display: flex;
  text-align: center;
}

.show-info .el-input {
  width: 450px;
}
</style>